package vip.xiaonuo.dev.modular.sms.util.hkust;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.xiaonuo.dev.api.DevConfigApi;

import javax.annotation.PostConstruct;
import java.util.Objects;

/**
 * 渠道获取工具类
 *
 * @author qinguangrui
 */
@Slf4j
@Component
public class ChannelUtils {
    private JSONObject channels;
    public String SMS_CONFIG_URL;
    public String SMS_CONFIG_ACCOUTID;
    public String SMS_CONFIG_ACCOUNTKEY;

    @Autowired
    private DevConfigApi devConfigApi;

    @PostConstruct
    public void init() {
        SMS_CONFIG_URL = devConfigApi.getValueByKey("SMS_CONFIG_URL");
        SMS_CONFIG_ACCOUTID = devConfigApi.getValueByKey("SMS_CONFIG_ACCOUTID");
        SMS_CONFIG_ACCOUNTKEY = devConfigApi.getValueByKey("SMS_CONFIG_ACCOUNTKEY");
    }

    /**
     * 获取渠道信息
     *
     * @param accountID  应用账号
     * @param accountKey 应用秘钥
     * @return JSONObject 返回结果
     * @author: qinguangrui
     */
    public JSONObject getChannels(String accountID, String accountKey) {
        JSONObject channelJson = JSON.parseObject(HttpUtils.httpGet(SMS_CONFIG_URL + Constant.CHANNEL_URL.replace("#accountID", accountID).replace("#accountKey", accountKey)));
        channels = channelJson;
        log.info(String.format("发送短信,获取应用下的渠道信息=%s", channelJson));
        return channelJson;
    }

    /**
     * 获取邮箱渠道
     *
     * @return JSONObject 返回结果
     * @author: qinguangrui
     */
    public JSONArray getEmailChannels() {
        if (Objects.isNull(channels)) {
            channels = getChannels(SMS_CONFIG_ACCOUTID, SMS_CONFIG_ACCOUNTKEY);
        }
        if (!Objects.isNull(channels) && !Objects.equals(channels.getInteger("errcode"), 0)) {
            return new JSONArray();
        }
        if (!Objects.isNull(channels) && channels.containsKey("data")
                && channels.getJSONObject("data").containsKey("email")) {
            return channels.getJSONObject("data").getJSONArray("email");
        }
        return new JSONArray();
    }

    /**
     * 获取短信渠道
     *
     * @return JSONObject 返回结果
     * @author: qinguangrui
     */
    public JSONArray getSmsChannels() {
        if (Objects.isNull(channels)) {
            channels = getChannels(SMS_CONFIG_ACCOUTID, SMS_CONFIG_ACCOUNTKEY);
        }
        if (!Objects.isNull(channels) && !Objects.equals(channels.getInteger("errcode"), 0)) {
            return new JSONArray();
        }
        if (!Objects.isNull(channels) && channels.containsKey("data")
                && channels.getJSONObject("data").containsKey("ydxy-mobile")) {
            return channels.getJSONObject("data").getJSONArray("ydxy-mobile");
        }
        return new JSONArray();
    }
}
